package com.danskin.wechat.webapi;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.danskin.wechat.entity.StoreInfo;
import com.danskin.wechat.model.AccessResponse;
import com.danskin.wechat.service.StoreInfoService;
import com.danskin.wechat.service.SysAreaService;
import com.danskin.wechat.service.impl.MapBaidu;
import com.danskin.wechat.util.ConvertUtils;
import com.danskin.wechat.util.JsonUtils;
import com.danskin.wechat.util.Page;
import com.danskin.wechat.util.Tools;

@Controller
@RequestMapping("api/store")
public class StoreInfoController extends BaseApiController{
	
	@Autowired
	private StoreInfoService storeInfoService;
	
	private final static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
	
	@Autowired
	private MapBaidu mapBaidu;
	
	/**
	 * 给前端提供 店铺列表
	 * @param map
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/getStoreList/{appId}", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String getStoreList(@RequestBody Map<String, Object> map,@PathVariable("appId") String appId){
		AccessResponse<List<Map<String,Object>> > access=new AccessResponse<List<Map<String,Object>> >();
		
		if (!map.containsKey("latitude")) {
			access.setErrorCode("1");
			access.setErrorMsg("纬度不能为空");
			return JsonUtils.objectToJson(access);
		}else if (!map.containsKey("pageIndex")) {
			access.setErrorCode("1");
			access.setErrorMsg("pageIndex不能为空");
			return JsonUtils.objectToJson(access);
		}else if (!map.containsKey("longitude")) {
			access.setErrorCode("1");
			access.setErrorMsg("经度不能为空");
			return JsonUtils.objectToJson(access);
		}
		Double latitude=Double.valueOf(String.valueOf(map.get("latitude"))) ;
		Double longitude=Double.valueOf(String.valueOf(map.get("longitude"))) ;
		String sPageIndex= map.get("pageIndex").toString();
		int pageIndex = ConvertUtils.getInt(sPageIndex);
		int pageSize = 10;
		Page page = new Page();
		page.setCurrentResult(pageIndex);
		page.setShowCount(pageSize);
		map.put("appId", appId);
		map.put("latitude", latitude);
		map.put("longitude", longitude);
		page.setMap(map);
		
		List<StoreInfo> list = storeInfoService.listPageStrore(page);
		List<Map<String,Object>> result=new ArrayList<Map<String,Object>>();
			if(list.size()>0){
				for (StoreInfo info : list) {
					Map<String,Object> mp=new HashMap<String, Object>();
					mp.put("sid", info.getId()); 
					mp.put("sname", info.getName()); 
					String p="";
					/*if(null!=info.getProvince()){
					 p+= areaService.getSysAreaByCode(info.getProvince());
					}
					if(null!=info.getCity()){
						 p += areaService.getSysAreaByCode(info.getCity());
					}
					if(null!=info.getDistrict()){
						p+= areaService.getSysAreaByCode(info.getDistrict());
					}*/
					mp.put("saddress", p+info.getAddress()); 
					mp.put("stell", info.getTelephone());
					
					mp.put("scode", info.getStoreCode());
					
					Map<String, Double> gcj02 = Convert_BD09_To_GCJ02(info.getLatitude().doubleValue(),info.getLongitude().doubleValue());
					mp.put("slat", gcj02.get("lat"));
					mp.put("slng", gcj02.get("lng"));
					if(null!=info.getLongitude()&&null!=info.getLatitude()){
						//mp.put("longkm",DecimalFormat( Tools.GetDistance(longitude, latitude, info.getLongitude().doubleValue(), info.getLatitude().doubleValue())));
					double dis=	Double.parseDouble(info.getJuli())/1000.00;
						if(dis<0.01){
							mp.put("longkm", 0);
						}else{
							mp.put("longkm", DecimalFormat(dis));
						}
						
					}else{
						mp.put("longkm", 0);
					}
					
					result.add(mp);
				}
				access.setErrorCode("0");
				access.setErrorMsg("成功");
				access.setData(result);
			}else{
				access.setErrorCode("1");
				access.setErrorMsg("获取店铺信息失败");
				access.setData(new ArrayList<Map<String,Object>>());
			}
		return JsonUtils.objectToJson(access);
	}
	/**
	 * 展示来自于李宁MDM的初始化门店信息      MDM实时推送
	 * @param info
	 * @param appId
	 * @return
	 */
	@RequestMapping(value = "/saveStoreInfo/{appId}", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String saveStoreInfo(@RequestBody Map<String, Object> map,@PathVariable("appId") String appId){
		AccessResponse<List<Map<String,Object>> > access=new AccessResponse<List<Map<String,Object>> >();
		
		if (!map.containsKey("latitude")) {
			access.setErrorCode("1");
			access.setErrorMsg("纬度不能为空");
			return JsonUtils.objectToJson(access);
		}else if (!map.containsKey("storeCode")) {
			access.setErrorCode("1");
			access.setErrorMsg("商店编号不能为空");
			return JsonUtils.objectToJson(access);
		}else if (!map.containsKey("longitude")) {
			access.setErrorCode("1");
			access.setErrorMsg("经度不能为空");
			return JsonUtils.objectToJson(access);
		}else if (!map.containsKey("name")) {
			access.setErrorCode("1");
			access.setErrorMsg("商店名不能为空");
			return JsonUtils.objectToJson(access);
		}else if (!map.containsKey("type")) {
			access.setErrorCode("1");
			access.setErrorMsg("商店类型不能为空");
			return JsonUtils.objectToJson(access);
		}
		StoreInfo storeInfo = Tools.toBean(map, StoreInfo.class);
		int i = storeInfoService.insertSelective(storeInfo, appId);
		if(i>0){
			access.setErrorCode("0");
			access.setErrorMsg("OK");
		}else{
			access.setErrorCode("1");
			access.setErrorMsg("fail");
		}
		return JsonUtils.objectToJson(access);
	}
	
	
	
	
	
	@RequestMapping(value = "/initStore/{appId}", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String initStore(@PathVariable("appId") String appId) throws Exception{
		Map<String, Object> map=new HashMap<>();
		int pageSize = 1000;
		Page page = new Page();
		page.setCurrentResult(1000);
		page.setShowCount(pageSize);
		map.put("mpId", 14);
		page.setMap(map);
		String string = mapBaidu.setlngAndlat(page);
		
		return string;
	}
	
	/**
	 * 百度经纬度转标准经纬度（腾讯，谷歌）
	 * @param lat
	 * @param lng
	 * @return
	 */
	public static Map<String, Double> Convert_BD09_To_GCJ02(double lat, double lng) {
		Map<String,Double> map=new HashMap<>();
		double x = lng - 0.0065, y = lat - 0.006;
		double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
		double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
		lng = z * Math.cos(theta);
		lat = z * Math.sin(theta);
		map.put("lat", lat);
		map.put("lng", lng);
		return map;
	}
	
	public String DecimalFormat(double f) {
		DecimalFormat df = new DecimalFormat("0.00");
		return df.format(f);
	}

}
